package com.cfc.stage1;

import org.junit.Test;

import java.util.Arrays;

/**
 * @description: 加一
 *   https://leetcode.cn/problems/plus-one/
 * @author: yangxuan10
 * @create: 2024-04-19 11:12
 **/
public class PlusOne {

    @Test
    public void test1() {
        int [] array = new int []{2,3,4};
        System.out.println(Arrays.toString(plusOne(array)));
    }

    public int[] plusOne(int[] digits) {
        int indexLength = digits.length -1;
        int tmp =digits[indexLength] +1;
        if (tmp == 10) {
            return carryHandler(indexLength,digits);
        } else {
            digits[indexLength] = tmp;
        }
        return digits;
    }

    public int[] carryHandler(int indexLength,int[] digits) {
        digits[indexLength] = 0;
        if (indexLength == 0) {
            int [] newArrays = new int [digits.length+1];
            newArrays[0] = 1;
            return newArrays;
        }
        int tmp = 0;
        int carry = 1;
        for (int i = indexLength-1;i >=0 ; i--) {
            tmp = digits[i] + carry;
            if (tmp == 10) {
                digits[i] = 0;
                if (i == 0) {
                    int [] newArrays = new int [digits.length+1];
                    newArrays[0] = 1;
                    return newArrays;
                }
            } else {
                digits[i] = tmp;
                break;
            }
        }
        return digits;
    }

}